﻿// ----------------------------------------------------------------------
//
// <copyright file="MainWindow.xaml.cs" company="TheAcidToy Inc" Date="2012">
//     TheAcidToy is a registered trademark of TheAcidToy Inc. All right reserved, copywrited: 2012
// </copyright>
//
// ------------------------------------------------------------------------

using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using _ACID_Cache_Cleaner.List_Helper;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using System.IO;
using System.ComponentModel;
using System.Windows.Threading;
using System.Data;
using System.Data.SQLite;
using HtmlAgilityPack;
using System.Runtime.InteropServices;
using System.Windows.Interop;
using System.Net;
using System.Deployment;
using System.Diagnostics;
using System.Reflection;
using System.Net.NetworkInformation;
using System.Text.RegularExpressions;

namespace _ACID_Cache_Cleaner
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        /// <summary>
        ///     Methods
        /// </summary>
        #region "Methods"
        BackgroundWorker worker = new BackgroundWorker();
        BackgroundWorker worker2 = new BackgroundWorker();
        BackgroundWorker worker3 = new BackgroundWorker();
        BackgroundWorker worker5 = new BackgroundWorker();
        BackgroundWorker ip_getter = new BackgroundWorker();
        Stopwatch st = new Stopwatch();
        ArrayList Links = new ArrayList();
        ArrayList P_Links = new ArrayList();
        Thread runner = new Thread(IMVU_Kill_Runner.check_IMVU);
        int clean = 0;
        //Settings.ini

        public string[] install_path =   {System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\[ACID]Cache Cleaner\\"),
                                             System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\[ACID]Cache Cleaner\\Settings\\"),
                                   System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\[ACID]Cache Cleaner\\Installers\\"),
                                  System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\[ACID]Cache Cleaner\\Images\\Resellers\\"),
                                  System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\[ACID]Cache Cleaner\\Images\\Products\\")};

        string[] folders = { System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\IMVU\\AssetCache"), 
                              System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\IMVU\\HttpCache"), 
                              System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\IMVU\\PixmapCache"),
                              System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\IMVUClient\\ui\\profile\\Cache")};

        public string[] Setting_path = { System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\[ACID]Cache Cleaner\\Settings\\Settings.ini")};

        long size = 0;
        int i = 0;
        int max = 0;

        [DllImport("user32.dll")]
        private extern static Int32 SetWindowLong(IntPtr hWnd, Int32 nIndex, Int32 dwNewLong);
        [DllImport("user32.dll")]
        private extern static Int32 GetWindowLong(IntPtr hWnd, Int32 nIndex);

        private const Int32 GWL_STYLE = -16;
        private const Int32 WS_MAXIMIZEBOX = 0x10000;
        private const Int32 WS_MINIMIZEBOX = 0x20000;

        private string img = "Img/offline_icon.png";
        private bool is_online = Online_Helper.IsConnectedToInternet();
        private bool use_img = true;

       

        #endregion

        public MainWindow()
        {
            folder_helper.check_folder(install_path);
            Load_ini.make_INI(Setting_path[0]);

            InitializeComponent();
            
            IniFile ini = new IniFile(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\[ACID]Cache Cleaner\\Settings\\Settings.ini"));          
            ini.IniWriteValue("Update", "Last_Update", DateTime.Now.ToString());
            if (!Online_Helper.IsConnectedToInternet())
            {
                use_img = false;
            }
            this.checkBox3.IsChecked = Load_ini.Get_INI_Bool("Cache", "Auto_Cache"); 
            /*IniFile ini = new IniFile(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\[ACID]Cache Cleaner\\Settings\\Settings.ini"));
            MessageBox.Show(ini.IniReadValue("Load", "Auto_Kill"));*/
            textBox1.Text = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)) + "\\IMVUClient\\";
            if (Load_ini.Get_INI_Bool("Load", "Auto_Del"))
            {
                this.checkBox1.IsChecked = true;
                this.checkBox2.IsChecked = true;
                this.checkBox2.IsEnabled = false;
                this.Cleaner_Start.Content = "Clean Folders";
                clean = 1;
            }
            if (Load_ini.Get_INI_Bool("Load", "Auto_Kill") || checkBox2.IsChecked == true)
            {
                checkBox2.IsChecked = true;
                IMVU_Helper.kill_IMVU("IMVUClient");
                button1.Visibility = Visibility.Hidden;
                runner.Start();
            }else if (IMVU_Helper.IsProcessOpen("IMVUClient"))
            {
                //Cleaner_Start.IsEnabled = false;
                if (!Load_ini.Get_INI_Bool("Load", "Auto_Kill") && !Load_ini.Get_INI_Bool("Load", "Auto_Del"))
                {
                    Cleaner_Start.IsEnabled = true;
                }
                else
                {
                    Cleaner_Start.IsEnabled = false;
                }
            }
            else
            {
                button1.Visibility = Visibility.Hidden;
            }    
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //http://icons.iconarchive.com/icons/laurent-baumann/blend/256/Location-File-icon.png
            IntPtr hWnd = new WindowInteropHelper(this).Handle;
            Int32 windowLong = GetWindowLong(hWnd, GWL_STYLE);
            windowLong = windowLong & ~WS_MAXIMIZEBOX;
            SetWindowLong(hWnd, GWL_STYLE, windowLong);
            IniFile ini = new IniFile(Setting_path[0]);

            /*loaders*/
            if (Size_Helper.get_IMVU_Ver() == Next_IMVU_Ver.get_Ver() || Next_IMVU_Ver.get_Ver() == "")
            {
                Update_But.Visibility = System.Windows.Visibility.Hidden;
                per.Visibility = System.Windows.Visibility.Hidden;
                dl_go.Visibility = System.Windows.Visibility.Hidden;
                IMVU_Ver.Content = "Current Version: " + Size_Helper.get_IMVU_Ver() + "\tLast Checked: " + ini.IniReadValue("Update", "Last_Update");
                ram_amout.Content = "Current IMVU Version: " + Size_Helper.get_IMVU_Ver() + "\tLast Checked: " + ini.IniReadValue("Update", "Last_Update");
                this.Title = "[ACID]Cache Cleaner (IMVU Version: " + Size_Helper.get_IMVU_Ver() + ")";
            }
            else
            {
                this.Title = "[ACID]Cache Cleaner (IMVU Version: " + Size_Helper.get_IMVU_Ver() + "  Next Version: " + Next_IMVU_Ver.get_Ver() + ")";
                ram_amout.Content = "Current IMVU Version: " + Size_Helper.get_IMVU_Ver() + "\tNext Version: " + Next_IMVU_Ver.get_Ver() + "\tLast Checked: " + ini.IniReadValue("Update", "Last_Update");
                IMVU_Ver.Content = "Current Version: " + Size_Helper.get_IMVU_Ver() + "\tNext Version: " + Next_IMVU_Ver.get_Ver();
                Update_But.Content = string.Format("Update to: '{0}'", Next_IMVU_Ver.get_Ver());
            }
            
            g_card.Content = "Video Card: "+Sys_Info.get_video() + "\t\tTotal Ram: " + Sys_Ram.get_ram();
            OS_Name.Content = Sys_Info.get_Windows() + Sys_Info.GetServicePack();
            if (is_online)
            {
                worker2.DoWork += new DoWorkEventHandler(worker2_DoWork);
                //worker2.WorkerSupportsCancellation = true;
                worker2.RunWorkerAsync();
            }
            else
            {
                tabControl1.Items.RemoveAt(2);
            }
            ip_getter.DoWork += new DoWorkEventHandler(ip_getter_DoWork);
            ip_getter.RunWorkerAsync();
            worker3.DoWork += new DoWorkEventHandler(worker3_DoWork);
            worker3.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker3_RunWorkerCompleted);
            worker3.RunWorkerAsync();
            this.Cursor = Cursors.Wait;
            A_Ver.Content = string.Format("Version: {0} \t\t Last Checked: {1}", ini.IniReadValue("Auto", "Version"), DateTime.Now);
            //A_Ver.Content = string.Format("Version: {0}", ini.IniReadValue("Auto", "Version"));
            textBox2.Text = ini.IniReadValue("Auto", "Auto_Clean_Timeout");
        }

        void ip_getter_DoWork(object sender, DoWorkEventArgs e)
        {
            IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
            TcpConnectionInformation[] tcpConnections = ipProperties.GetActiveTcpConnections();
            string flag_code = "";
            while (true)
            {
                foreach (TcpConnectionInformation tcpInfo in tcpConnections)
                {
                    IP_log IP = new IP_log();
                    //MessageBox.Show(GetCountryFlag(tcpInfo.RemoteEndPoint.Address.ToString()));
                    //IP.flag = "Flags/" + GetCountryFlag(tcpInfo.RemoteEndPoint.Address.ToString()) + ".png";
                    try
                    {
                        IPHostEntry hostInfo = Dns.GetHostEntry(tcpInfo.RemoteEndPoint.Address);
                        if (hostInfo.HostName != "")
                        {
                            IP.remote_ip = hostInfo.HostName;
                        }
                        else
                        {
                            IP.remote_ip = tcpInfo.RemoteEndPoint.Address.ToString();
                        }
                    }
                    catch (Exception ex)
                    {
                        IP.remote_ip = tcpInfo.RemoteEndPoint.Address.ToString();
                    }
                    if (Get_Code(tcpInfo.RemoteEndPoint.Address.ToString()) == "--")
                    {
                        IP.flag = "";
                    }
                    else
                    {
                        IP.flag = "Flags"+Get_Code(tcpInfo.RemoteEndPoint.Address.ToString()).ToLower() + ".png";
                    }
                    //flag_code += Get_Code(tcpInfo.RemoteEndPoint.Address.ToString()) + " - ";
                    IP.status = tcpInfo.State.ToString();
                    IP.local_ip = tcpInfo.LocalEndPoint.ToString();

                    IP.port = tcpInfo.RemoteEndPoint.Port.ToString();
                    listView3.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate()
                    {
                        listView3.Items.Add(IP);
                    }));
                }
                //MessageBox.Show(flag_code);
                Thread.Sleep(60000);
                listView3.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate()
                {
                    listView3.Items.Clear();
                }));
            }
        }

        public string Get_Code(string IP)
        {
            CountryLookupProj.CountryLookup con = new CountryLookupProj.CountryLookup("GEO_Data/GeoIP.dat");
            return con.lookupCountryCode(IP);
        }

        void worker2_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                var web = new HtmlWeb();
                var doc = web.Load("http://imvucreditresellers.com/");

                foreach (var node in doc.DocumentNode.SelectNodes("//div[@id='resellers']//div[@class='reseller']//a[@href]"))
                {
                    Resell resell = new Resell();
                    string[] lines = node.InnerText.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
                    resell.title = lines[2];
                    resell.url = node.Attributes["href"].Value;
                    Links.Add(node.Attributes["href"].Value);
                    string val = node.GetAttributeValue("wtf", string.Empty);
                    if (val == string.Empty)
                    {
                        string file_ext = node.SelectSingleNode("img[@src]").Attributes["src"].Value.Split('.')[1];
                        resell.resell_img = File_elper.chk_image(lines[2].ToString().Split('-')[0].TrimEnd().GetHashCode() + "." + file_ext, install_path[3], "http://imvucreditresellers.com/" + node.SelectSingleNode("img[@src]").Attributes["src"].Value, true);//"http://imvucreditresellers.com/" + node.SelectSingleNode("img[@src]").Attributes["src"].Value;
                        
                        //MessageBox.Show(lines[2].ToString().Split('-')[0].TrimEnd().GetHashCode() + "." + file_ext);
                    }
                    listBox1.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate()
                    {
                        listBox1.Items.Add(resell);
                    }));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void Cleaner_Start_Click_1(object sender, RoutedEventArgs e)
        {
            if (clean == 0 || clean == 1)
            {
                runner.IsBackground = true;
                if (!runner.IsAlive && clean == 1)
                {
                    runner.Start();
                }
                if (listView1.Items.Count > 0)
                {
                    listBox1.Items.Clear();
                    max = 0;
                    i = 0;
                    size = 0;
                }
                this.Cursor = Cursors.Wait;
                this.Cleaner_Start.IsEnabled = false;
                st.Start();
                worker.DoWork += new DoWorkEventHandler(worker_DoWork);
                worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
                worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
                worker.WorkerReportsProgress = true;
                worker.RunWorkerAsync();
            }
            if (clean == 2)
            {
                if (runner.IsAlive)
                    runner.Abort();
                System.Diagnostics.Process.Start(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)) + "\\IMVUClient\\IMVUClient.exe");
            }
            if (clean == 3)
            {
                this.Close();
            }
        }

        void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.progressBar1.Value = e.ProgressPercentage;
            this.label2.Content = e.ProgressPercentage + "%";
        }

        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            switch (clean)
            {
                case 0:
                    if (listView1.Items.Count > 0)
                    {
                        clean = 1;
                        if (!IMVU_Helper.IsProcessOpen("IMVUClient"))
                        {
                            Cleaner_Start.Content = "Clean Files";
                        }
                        else
                        {
                            MessageBox.Show("Looks like you need to kill the IMVU process");
                            Cleaner_Start.Content = "Clean Files";
                            Cleaner_Start.IsEnabled = false;
                        }
                    }
                    else
                    {
                        if (is_online)
                        {
                            clean = 2;
                            runner.Abort();
                            Cleaner_Start.Content = "Run IMVU";
                        }
                        else
                        {
                            clean = 3;
                            runner.Abort();
                            Cleaner_Start.Content = "Close Program";
                        }
                    }
                    break;
                case 1:
                    if (is_online)
                    {
                        clean = 2;
                        runner.Abort();
                        Cleaner_Start.Content = "Run IMVU";
                    }
                    else
                    {
                        clean = 3;
                        runner.Abort();
                        Cleaner_Start.Content = "Close Program";
                    }
                    break;
                default:
                    clean = 3;
                    runner.Abort();
                    Cleaner_Start.Content = "Close Program";
                    break;
            }
            this.Cursor = Cursors.Arrow;
            this.Cleaner_Start.IsEnabled = true;
            st.Stop();
            TimeSpan t = TimeSpan.FromMilliseconds(st.Elapsed.TotalMilliseconds);
            label3.Content = "Run Time: " + t.Hours + ":" + t.Minutes + ":" + t.Seconds;
        }

        //Worker
        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            int p = 0, m = 0,u = 0;
            int[] f_count = {0};
            //textBox1.Text = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)) + "\\IMVUClient\\";
            if (clean == 0)
            {
                foreach (string me in folders)
                {
                    var info = new DirectoryInfo(me);
                    //FileInfo[] file = info.GetFiles("*.*", SearchOption.TopDirectoryOnly);
                    var file = new List<FileInfo>(info.GetFiles("*.*", SearchOption.TopDirectoryOnly));
                    max += file.Count;
                    textBox1.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate()
                    { if (me != null) this.textBox1.Text = me; }));

                    tabItem6.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate()
                    {
                        tabItem6.Header = "All Files (Count: "+(f_count[0] = f_count[0] += file.Count).ToString(CultureInfo.InvariantCulture) +")";
                    }));

                    progressBar1.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate()
                    {
                        progressBar1.Maximum = file.Count;
                       
                    }));
                    foreach (var fi in file)
                    {
                        size += fi.Length;
                        double percentage = (i + 1) / file.Count() * 100;
                        var row = new LVData {text = fi.Name, path = fi.FullName};
                        if (fi.Name.ToLower().Contains("produ"))
                        {
                            var p_row = new P_LVData
                                            {
                                                p_text = fi.Name,
                                                p_path = fi.FullName,
                                                p_size = Size_Helper.GetFileSize(fi.Length)
                                            };

                            listView4.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate()
                            {
                                listView4.Items.Add(p_row);
                            }));
                        }


                        if (me.ToLower().Contains("\\IMVUClient\\ui\\profile\\Cache".ToLower()))
                        {
                            var ui = new UI_LVData
                                               {
                                                   ui_text = fi.Name,
                                                   ui_path = fi.FullName,
                                                   ui_size = Size_Helper.GetFileSize(fi.Length)
                                               };

                            listView5.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate()
                            {
                                listView5.Items.Add(ui);
                            }));
                        }

                        if (!me.ToLower().Contains("\\IMVUClient\\ui\\profile\\Cache".ToLower()) && !fi.Name.ToLower().Contains("produ"))
                        {
                            var misc = new Misc_LVData
                                                   {
                                                       misc_text = fi.Name,
                                                       misc_path = fi.FullName,
                                                       misc_size = Size_Helper.GetFileSize(fi.Length)
                                                   };

                            listView6.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate()
                            {
                                listView6.Items.Add(misc);
                            }));
                        }
                        row.size = Size_Helper.GetFileSize(fi.Length);
                        listView1.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate()
                        {
                            listView1.Items.Add(row);
                        }));

                        label1.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate()
                        {
                            label1.Content = string.Format("Size: {0}", Size_Helper.GetFileSize(size));
                        }));
                        i = i + 1;
                        progressBar1.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate()
                            {
                                progressBar1.Value = i;
                            }));
                        label3.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate()
                            {
                                TimeSpan t = TimeSpan.FromMilliseconds(st.Elapsed.TotalMilliseconds);
                                label3.Content = "Run Time: " + t.Hours + ":" + t.Minutes + ":" + t.Seconds;
                            }));
                        label2.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate()
                        {
                            label2.Content = int.Parse(Math.Truncate(((double)max * (double)i) / 100).ToString(CultureInfo.InvariantCulture)) + "%";
                        }));
                    }
                }
            }
            else
            {
                foreach (string me in folders)
                {
                    var info = new DirectoryInfo(me);
                    //FileInfo[] file = info.GetFiles("*.*", SearchOption.TopDirectoryOnly);
                    var file = new List<FileInfo>(info.GetFiles("*.*", SearchOption.TopDirectoryOnly));
                    //Debug.Print(file.Length.ToString());
                    progressBar1.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate()
                    {
                        progressBar1.Maximum = file.Count;
                    }));

                    foreach (FileInfo fi in file)
                    {
                        size += fi.Length;
                        double percentage = (i + 1) / file.Count() * 100;
                        var row = new LVData
                                         {text = fi.Name, path = fi.FullName, size = Size_Helper.GetFileSize(fi.Length)};
                        listView1.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate()
                        {
                            listView1.Items.Add(row);
                        }));
                        label1.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate()
                        {
                            label1.Content = string.Format("Size: {0}", Size_Helper.GetFileSize(size));
                        }));
                        i = i + 1;
                        progressBar1.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate()
                        {
                            progressBar1.Value = i;
                        }));
                        label3.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate()
                        {
                            TimeSpan t = TimeSpan.FromMilliseconds(st.Elapsed.TotalMilliseconds);
                            label3.Content = "Run Time: " + t.Hours + ":" + t.Minutes + ":" + t.Seconds;
                        }));
                        label2.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate()
                        {
                            label2.Content = int.Parse(Math.Truncate((double)i * (double)max / 100).ToString(CultureInfo.InvariantCulture)) + "%";
                        }));
                        fi.Delete();
                    }
                }
            }
        }

        private void listBox1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (listBox1.SelectedIndex != -1)
            {
                Process.Start(Links[listBox1.SelectedIndex].ToString());
            }
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            IMVU_Helper.kill_IMVU("IMVUClient");
            if (!runner.IsAlive)
            {
                runner.Start();
            }
            Thread.Sleep(1000);
            if (IMVU_Helper.IsProcessOpen("IMVUClient"))
            {
                Cleaner_Start.IsEnabled = false;
            }
            else
            {
                Cleaner_Start.IsEnabled = true;
                MessageBox.Show("If IMVU ask if you wish to restart it say 'No'");
                button1.Visibility = Visibility.Hidden;
            }
        }
        int dl = 0;
        private void Update_But_Click(object sender, RoutedEventArgs e)
        {
            if (File.Exists(install_path[2] + "IMVUClient" + Next_IMVU_Ver.get_Ver() + ".exe"))
            {
                MessageBox.Show("Installing IMVU Version '" + Next_IMVU_Ver.get_Ver() + "'");
                System.Diagnostics.Process.Start(install_path[2] + "\\IMVUClient" + Next_IMVU_Ver.get_Ver() + ".exe");
                Update_But.IsEnabled = false;
            }
            else
            {
                if (Next_IMVU_Ver.get_Ver() == "467.24")
                    MessageBox.Show("This version is know to have tons of bugs and is not recommended");
                WebClient client = new WebClient();
                client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
                client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);

                // Starts the download
                client.DownloadFileAsync(new Uri("http://static-akm.imvu.com/imvufiles/installers/InstallIMVU_" + Next_IMVU_Ver.get_Ver() + ".exe"), install_path[2] + "IMVUClient" + Next_IMVU_Ver.get_Ver() + ".exe");

                Update_But.IsEnabled = false;
            }

        }

        void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            MessageBox.Show("Download of IMVU Version '" + Next_IMVU_Ver.get_Ver() + "' is complete, press the '" + string.Format("Update to: '{0}'", Next_IMVU_Ver.get_Ver()) + "' button to install.");
            Update_But.IsEnabled = true;
        }

        void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            double bytesIn = double.Parse(e.BytesReceived.ToString(CultureInfo.InvariantCulture));
            double totalBytes = double.Parse(e.TotalBytesToReceive.ToString(CultureInfo.InvariantCulture));
            double percentage = bytesIn / totalBytes * 100;

            per.Content = int.Parse(Math.Truncate(percentage).ToString(CultureInfo.InvariantCulture)).ToString(CultureInfo.InvariantCulture) + "%";

            dl_go.Value = int.Parse(Math.Truncate(percentage).ToString(CultureInfo.InvariantCulture));
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            IniFile ini = new IniFile(Setting_path[0]);
            ini.IniWriteValue("Load", "Auto_Del", (checkBox1.IsChecked != null && checkBox1.IsChecked.Value).ToString(CultureInfo.InvariantCulture));
            ini.IniWriteValue("Load", "Auto_Kill", (checkBox2.IsChecked != null && checkBox2.IsChecked.Value).ToString(CultureInfo.InvariantCulture));
            ini.IniWriteValue("Cache", "Auto_Cache", (checkBox3.IsChecked != null && checkBox3.IsChecked.Value).ToString(CultureInfo.InvariantCulture));
            if (textBox2.Text != null) ini.IniWriteValue("Auto", "Auto_Clean_Timeout", textBox2.Text);
        }

        private void listView2_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (listView2.SelectedIndex != -1)
            {
                Process.Start(P_Links[listView2.SelectedIndex].ToString());
            }
        }

        private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            Process.Start(e.Uri.AbsoluteUri);
            e.Handled = true;
        }

        void worker3_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.Cursor = Cursors.Arrow;
        }


        void worker3_DoWork(object sender, DoWorkEventArgs e)
        {
            var dt = new DataTable();
            var cn = new SQLiteConnection();
            try
            {
                cn.ConnectionString = string.Format("Data Source={0}", System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)) + "\\IMVU\\productInfoCache.db");
                cn.Open();

                var cmd = new SQLiteCommand();
                cmd.Connection = cn;
                cmd.CommandText = "SELECT * FROM products";
                //cmd.CommandType = System.Data.CommandType.Text;

                SQLiteDataReader reader = cmd.ExecuteReader();

                dt.Load(reader);

                foreach (DataRow dr in dt.Rows)
                {
                    Item_DB item = new Item_DB();
                    string fileExt = System.IO.Path.GetExtension(dr["products_image"].ToString());
                    if (File_elper.img_real(dr["id"] + "." + fileExt, install_path[4]) != "offline_icon.png")
                    {            
                        item.img = File_elper.chk_image(dr["id"].ToString() + "." + fileExt, install_path[4], dr["products_image"].ToString(), Load_ini.Get_INI_Bool("Cache", "Auto_Cache"));
                    }
                    else
                    {
                        item.img = img;
                    }
                    if (dr["manufacturers_name"].ToString().Length <= 1)
                    {
                        item.dev_url = "http://www.imvu.com/";
                        item.P_Links = "http://www.imvu.com/";
                        item.dev = "Unknown";
                    }
                    else
                    {
                        item.dev = "By, " + dr["manufacturers_name"];
                        item.dev_url = "http://www.imvu.com/shop/web_search.php?manufacturers_id=" + dr["manufacturers_id"];
                        item.P_Links = "http://www.imvu.com/shop/product.php?products_id=" + dr["id"];
                    }
                    P_Links.Add("http://www.imvu.com/shop/product.php?products_id=" + dr["id"].ToString());
                    item.id = "Item ID: " + dr["id"];
                    item.name = dr["products_name"].ToString();
                    listView2.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate()
                    {
                        listView2.Items.Add(item);
                    }));
                }
            }
            catch (Exception ex)
            {
                //display any exeptions
                MessageBox.Show(ex.Message);
            }
            finally
            {
                cn.Close();
            }
        }

        private void Hyperlink2_Click(object sender, RoutedEventArgs e)
        {
            Clipboard.SetText(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)) + "\\IMVUClient\\", TextDataFormat.Text);
        }

        private void checkBox1_Click(object sender, RoutedEventArgs e)
        {
            if (checkBox1.IsChecked == true)
            {
                checkBox2.IsEnabled = false;
                checkBox2.IsChecked = true;
            }
            if (checkBox1.IsChecked == false)
            {
                checkBox2.IsEnabled = true;
                checkBox2.IsChecked = false;
            }
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            Process prc = Process.GetCurrentProcess();
            prc.Kill();
        }

        private void button3_Click(object sender, RoutedEventArgs e)
        {
            if (Size_Helper.get_IMVU_Ver() == Next_IMVU_Ver.get_Ver() || Next_IMVU_Ver.get_Ver() == "")
            {
                IMVU_Ver.Content = "Current Version: " + Size_Helper.get_IMVU_Ver() + "\tLast Checked: " + DateTime.Now;
            }
            else
            {
                Update_But.Visibility = System.Windows.Visibility.Visible;
                per.Visibility = System.Windows.Visibility.Visible;
                dl_go.Visibility = System.Windows.Visibility.Visible;
                IMVU_Ver.Content = "Current Version: " + Size_Helper.get_IMVU_Ver() + "\tNext Version: " + Next_IMVU_Ver.get_Ver();
                Update_But.Content = string.Format("Update to: '{0}'", Next_IMVU_Ver.get_Ver()); 
            }
        }

        private void textBox2_TextChanged(object sender, TextChangedEventArgs e)
        {
            var textBox = sender as TextBox;
            int iValue = -1;

            if (textBox != null && Int32.TryParse(textBox.Text, out iValue) == false)
            {
                var textChange = e.Changes.ElementAt<TextChange>(0);
                int iAddedLength = textChange.AddedLength;
                int iOffset = textChange.Offset;

                textBox.Text = textBox.Text.Remove(iOffset, iAddedLength);
            }
        }

        private static bool IsTextAllowed(string text)
        {
            var regex = new Regex("[^0-9.-]+"); //regex that matches disallowed text
            return !regex.IsMatch(text);
        }

        private void button4_Click(object sender, RoutedEventArgs e)
        {
            var ini = new IniFile(Setting_path[0]);
            A_Ver.Content = string.Format("Version: {0} \t\t Last Checked: {1}", ini.IniReadValue("Auto", "Version"), DateTime.Now);
        }
    }
}